import { App, defineComponent, h, Plugin, reactive, ref, watch } from 'vue';
import { ElPagination } from 'element-plus';
/**
 * 通用的分页组件
 */
export const CommonPagination = defineComponent({
  name: 'CommonPagination',
  props: {
    currentPage: {
      type: Number,
      default: 1
    },
    total: {
      type: Number,
      default: 0
    },
    currentPageSize: {
      type: Number,
      default: 10
    }
  },
  emits: ['update:currentPageSize', 'update:currentPage', 'changePage'],
  setup (props, { emit }) {
    const total = ref<number>(props.total);
    const currentPage = ref<number>(props.currentPage);
    const currentPageSize = ref<number>(props.currentPageSize);
    const pageSizes = reactive<number[]>([10, 30, 50, 100]);
    watch(currentPageSize, newVal => {
      emit('update:currentPageSize', newVal);
      emit('changePage', currentPage.value);
    });
    watch(currentPage, newVal => {
      emit('update:currentPage', newVal);
      emit('changePage', newVal);
    });
    watch(props, newVal => {
      total.value = props.total;
      currentPage.value = props.currentPage;
      currentPageSize.value = props.currentPageSize;
    });
    return () => {
      return <ElPagination
        background
        layout='total, sizes, prev, pager, next, jumper'
        v-model:currentPage={currentPage.value}
        v-model:pageSize={currentPageSize.value}
        pageSizes={pageSizes}
        total={total.value}></ElPagination>;
    };
  }
});

const plugin: Plugin = {
  install (app: App, options?: {[key: string]: any}) {
    app.component(CommonPagination.name, CommonPagination);
  }
};

export default plugin;
